package com.lanzuo.yxd.scanner.scanner;

import com.lanzuo.yxd.scanner.dto.SubmitResult;

import java.util.concurrent.TimeoutException;

/**
 * @author eric
 * 扫描结果的容器，用于主线程阻塞和唤醒
 */
public class ScanResultHolder {
    private SubmitResult panelResult;
    private Boolean completed = false;
    private Exception error;

    public synchronized void complete(SubmitResult panelPass) {
        this.panelResult = panelPass;
        this.completed = true;
        // 唤醒等待线程
        notifyAll();
    }

    public synchronized void fail(Exception e) {
        this.error = e;
        this.completed = true;
        notifyAll();
    }

    public synchronized boolean isCompleted() {
        return completed;
    }

    public synchronized Exception getError() {
        return error;
    }

    /**
     * 主线程调用：等待结果（带超时）
     */
    public synchronized SubmitResult waitForResult(long timeoutMs) throws InterruptedException, TimeoutException {
        long start = System.currentTimeMillis();
        // 防止虚假唤醒
        while (!completed) {
            long elapsed = System.currentTimeMillis() - start;
            if (elapsed >= timeoutMs) {
                throw new TimeoutException("扫码等待超时");
            }
            wait(timeoutMs - elapsed);
        }

        if (error != null) {
            throw new RuntimeException("扫码失败", error);
        }

        return panelResult;
    }
}